package email

import (
	"fmt"
	"log"

	"gopkg.in/gomail.v2"
)

// EmailConfig 邮件配置结构
type EmailConfig struct {
	Host     string
	Port     int
	Username string
	Password string
}

// DefaultEmailConfig 默认邮件配置
var DefaultEmailConfig EmailConfig

// InitEmailConfig 初始化邮件配置
func InitEmailConfig(host string, port int, username, password string) {
	DefaultEmailConfig = EmailConfig{
		Host:     host,
		Port:     port,
		Username: username,
		Password: password,
	}
}

// SendVerificationCode 发送验证码邮件
func SendVerificationCode(toEmail string, code string) error {
	if DefaultEmailConfig.Host == "" {
		// 使用默认配置（仅用于测试，实际使用时需要设置真实配置）
		InitEmailConfig("smtp.example.com", 587, "your-email@example.com", "your-password")

		// 在实际环境中，应该返回错误而不是使用默认配置
		log.Printf("Warning: Email not sent - using default config. To: %s, Code: %s", toEmail, code)
		return nil
	}

	m := gomail.NewMessage()
	m.SetHeader("From", DefaultEmailConfig.Username)
	m.SetHeader("To", toEmail)
	m.SetHeader("Subject", "验证码 - 您的账号安全验证")
	m.SetBody("text/html", fmt.Sprintf(`
	<div style="background-color: white; border-radius: 4px; border: 1px solid #e4e6eb; padding: 0px 10px; box-shadow: 0px 0px 10px 1px #e4e6eb;">
      <div style="border-bottom: 1px solid #e4e6eb; padding: 12px 0px 8px 0px;">
          <h1>欢迎使用!</h1>
      </div>
      <p>您的验证码为<span style="font-size: 22px; color: #4848FF; font-weight: bold;">%s</span>，请在<span style="color: #F56C6C; ">10分钟</span>内完成操作，如非本人操作，请忽略！</p>
    </div>
	`, code))

	d := gomail.NewDialer(
		DefaultEmailConfig.Host,
		DefaultEmailConfig.Port,
		DefaultEmailConfig.Username,
		DefaultEmailConfig.Password,
	)

	// 发送邮件
	return d.DialAndSend(m)
}
